package com.xuxingcan.findmyvoice.Util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.rey.material.app.DialogFragment;
import com.xuxingcan.findmyvoice.Activity.BaseActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;

/**
 * Created by xuxingcan on 16-4-4.
 */
public class UpdateUtil {
    private static final String UPDATE_CLASS = "XXC_UPDATE_CLASS";
    private static final String UPDATE_VERSION_CODE = "VERSION_CODE";
    private static final String UPDATE_FILE_URL = "FILE_URL";
    private static final String UPDATE_FILE_MD5 = "FILE_MD5";
    private static final String UPDATE_MESSAGE = "UPDATE_MESSAGE";

    /**
     * cannot in UI
     */
    public static void checkUpdateInBackgroundThread(final BaseActivity baseActivity) {
        if (!isWifiConnected(baseActivity)) {
            return;
        }
        final Handler mHandler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        return;
                    }
                    AVQuery<AVObject> query = new AVQuery<>(UPDATE_CLASS);
                    query.setLimit(1);
                    AVObject mAvObject = query.find().get(0);
                    if (mAvObject.getInt(UPDATE_VERSION_CODE) > getVersionCode(baseActivity)) {
                        String url = mAvObject.getString(UPDATE_FILE_URL);
                        String md5 = mAvObject.getString(UPDATE_FILE_MD5);
                        final String updateMsg = mAvObject.getString(UPDATE_MESSAGE);
                        if (url != null) {
                            File dir = new File(Environment.getExternalStorageDirectory(), "FindYourVoice");
                            if (dir.exists()) {
                                if (!dir.isDirectory()) {
                                    dir.delete();
                                    dir.mkdir();
                                }
                            } else {
                                dir.mkdir();
                            }
                            final File apkFile = new File(dir, "update.apk");
                            if (apkFile.exists() && md5.equalsIgnoreCase(getFileMD5(apkFile))) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        String[] msgs = updateMsg.split("&&&");
                                        String msg = "";
                                        for (String s : msgs) {
                                            msg += s + "\n";
                                        }
                                        baseActivity.showDialog("发现新版本", msg + "（已在WIFI下下载完毕!）", "更新", null, new BaseActivity.DialogCallback() {
                                            @Override
                                            public boolean onPositiveActionClicked(DialogFragment fragment) {
                                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                                intent.setDataAndType(Uri.fromFile(apkFile),
                                                        "application/vnd.android.package-archive");
                                                baseActivity.startActivity(intent);
                                                return false;
                                            }

                                            @Override
                                            public boolean onNegativeActionClicked(DialogFragment fragment) {
                                                return false;
                                            }
                                        });
                                    }
                                });
                                return;
                            }
                            URLConnection con = new URL(url).openConnection();
                            InputStream is = con.getInputStream();
                            byte[] bs = new byte[1024];
                            int len;
                            OutputStream os = new FileOutputStream(apkFile);
                            while ((len = is.read(bs)) != -1) {
                                os.write(bs, 0, len);
                            }
                            os.close();
                            is.close();
//                            if (apkFile.exists() && md5.equalsIgnoreCase(getFileMD5(apkFile))) {
//                                mHandler.post(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        baseActivity.showDialog("发现新版本", updateMsg + "\n（已在WIFI下下载完毕!）", "更新", null, new BaseActivity.DialogCallback() {
//                                            @Override
//                                            public boolean onPositiveActionClicked(DialogFragment fragment) {
//                                                Intent intent = new Intent(Intent.ACTION_VIEW);
//                                                intent.setDataAndType(Uri.fromFile(apkFile),
//                                                        "application/vnd.android.package-archive");
//                                                baseActivity.startActivity(intent);
//                                                return false;
//                                            }
//
//                                            @Override
//                                            public boolean onNegativeActionClicked(DialogFragment fragment) {
//                                                return false;
//                                            }
//                                        });
//                                    }
//                                });
//                                return;
//                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
        }).start();
    }

    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    public static String getFileMD5(File file) {
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}
